package app.poller.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import app.poller.R;
import app.poller.entities.Contact;

public class ContactArrayAdapter extends ArrayAdapter<Contact>{
	

	public ContactArrayAdapter(Context context, int textViewResourceId) {
		super(context, textViewResourceId);
	}
	
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		ViewHolder vh;
		
		if(convertView == null) {
			LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			vh = new ViewHolder();
			convertView = (RelativeLayout) inflater.inflate(R.layout.contact_row, null, false);
			vh.contactName = (TextView) ((RelativeLayout) convertView).findViewById(R.id.contact_name);
			vh.contactNumber = (TextView) ((RelativeLayout) convertView).findViewById(R.id.contact_number);
			vh.contactDeleteButton = (Button) ((RelativeLayout) convertView).findViewById(R.id.delete_contact_button);
			convertView.setTag(vh);
		}
		else {
			vh = (ViewHolder) convertView.getTag();
		}
		
		Contact listItem = getItem(position);
		vh.contactName.setText(listItem.getContactName());
		vh.contactNumber.setText(listItem.getContactPhoneNumber());
		vh.contactDeleteButton.setText("delete");
		vh.contactDeleteButton.setTag(position);
		vh.contactDeleteButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				remove(getItem((Integer)v.getTag()));
				notifyDataSetChanged();
			}
		});
		
		return convertView;
	}
	
	
	
	public static class ViewHolder {
		TextView contactName;
		TextView contactNumber;
		Button contactDeleteButton;
	}
}
